package com.sc.VenusQueryBeta.ui.fragments.account.zhuanma;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIDateTimeSaveListener;
import com.dou361.dialogui.widget.DateSelectorWheelView;
import com.example.zhouwei.library.CustomPopWindow;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.PopAdapter;
import com.sc.VenusQueryBeta.adapter.account.zhuanma.Zhuanma01Adapter;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.account.zhuanma.ZhuanMa01Contract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.account.CurrencyListBean;
import com.sc.VenusQueryBeta.model.bean.account.zhuanma.ZhuanMaList1;
import com.sc.VenusQueryBeta.model.bean.login.QueryRegisBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.account.zhuanma.ZhuanMa01Presenter;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.MaterialHeader;

import static android.view.Gravity.CENTER;

public class ZhuanMa01Fragment extends BaseMVPCompatFragment<ZhuanMa01Contract.ZhuanMa01Presenter> implements ZhuanMa01Contract.IZhuanMa01View, BaseQuickAdapter.RequestLoadMoreListener {

    private static ZhuanMa01Fragment fragment;
    @BindView(R.id.ibtn_zhuanma_back)
    ImageButton ibtnZhuanmaBack;
    @BindView(R.id.vip_uservip_user_infornation)
    RecyclerView vipUservipUserInfornation;
    @BindView(R.id.ptr_class)
    PtrClassicFrameLayout ptrClass;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.total_money)
    TextView totalMoney;
    @BindView(R.id.chooise_company)
    TextView chooiseCompany;
    @BindView(R.id.chooise_time)
    TextView chooiseTime;

    private QueryRegisBean queryRegisBean;
    private int clientindex;
    private String year;
    private String month;
    private int roomid;
    private String time1;
    private String time2;
    private UsersLoginBean loginBean;
    private View headView;
    private Zhuanma01Adapter zhuanma01Adapter;
    private String roomname;
    private boolean isUpdate;
    private View footView;
    private View errorView;
    private int type;
    private PopAdapter popAdapter;
    private CustomPopWindow mClubPopWindow;
    private RecyclerView clubrecyclerView;
    private CurrencyListBean mallRoomListBean;
    private String currency;

    public static ZhuanMa01Fragment newInstance(QueryRegisBean queryRegisBean, int clientindex, String roomyear, String roommonth,
                                                int roomId, int type, String currency) {
        Bundle args = new Bundle();
        args.putInt(Constants.CLIENTINDEX, clientindex);
        args.putSerializable(Constants.QUERY_SETTING, queryRegisBean);
        args.putString(Constants.YEAR, roomyear);
        args.putString(Constants.MONTH, roommonth);
        args.putInt(Constants.ROOMID, roomId);
        args.putInt(Constants.TYPE, type);
//        args.putString(Constants.ROOMNAME, roomname);
        args.putString(Constants.CURRENCYNAMECN, currency);
        fragment = new ZhuanMa01Fragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return ZhuanMa01Presenter.newInstance();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_zhuan_ma01_fragment;
    }

    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        chooiseCompany.setText(currency);
        zhuanma01Adapter = new Zhuanma01Adapter(R.layout.item_zhuanma01);
        vipUservipUserInfornation.setAdapter(zhuanma01Adapter);
        vipUservipUserInfornation.setLayoutManager(new LinearLayoutManager(mContext));
//        initHeadView();
        //request
//        showProgressDialog("請稍等...");
        initClub();
        reFreshListener();//下拉刷新

    }

    @Override
    public void showNetworkError(Throwable throwable) {
//        zhuanma01Adapter.setEmptyView(errorView);
        hideProgressDialog();
    }

    @Override
    public void showLoadMoreError() {
        zhuanma01Adapter.loadMoreFail();
        hideProgressDialog();
    }

    @Override
    public void showNoMoreData() {
        zhuanma01Adapter.loadMoreEnd(true);
//        zhuanma01Adapter.setFooterView(footView);
//        ToastUtils.showToast("已经加载全部数据了");
    }

    /**
     * 选择集团小窗口
     */
    private void initClub() {
        View contentView = LayoutInflater.from(mActivity).inflate(R.layout.pop_list, null);
        //创建并显示popWindow
        mClubPopWindow = new CustomPopWindow.PopupWindowBuilder(mActivity)
                .setView(contentView)
                .setView(contentView).setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                        lp.alpha = 1f;
                        mActivity.getWindow().setAttributes(lp);
                    }
                })
                .create();
        clubrecyclerView = contentView.findViewById(R.id.recyclerView);

    }

    @Override
    public void shoZhuanmaData1Success(final ZhuanMaList1 zhuanMaList1) {
        totalMoney.setText(zhuanMaList1.getChipsnumSum() + getString(R.string.wan));
        //布局处理
        if (zhuanMaList1.getList() != null && zhuanMaList1.getList().size() > 0) {
            ptrClass.setVisibility(View.VISIBLE);
            tvEmpty.setVisibility(View.GONE);
        } else {
            ptrClass.setVisibility(View.GONE);
            tvEmpty.setVisibility(View.VISIBLE);
        }
        if (zhuanma01Adapter.getData().size() == 0) {
            initRecycleView(zhuanMaList1);
        } else {
            if (isUpdate) {
                isUpdate = false;
                if (zhuanMaList1.getList() != null && zhuanMaList1.getList().size() > 0) {
                    zhuanma01Adapter.setNewData(zhuanMaList1.getList());
                }
            } else {
                if (zhuanMaList1.getList() != null && zhuanMaList1.getList().size() > 0) {
                    zhuanma01Adapter.addData(zhuanMaList1.getList());
                }
            }

        }
//        zhuanma01Adapter.addHeaderView(headView);
        zhuanma01Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                start(ZhuanMa02Fragment.newInstance(queryRegisBean, clientindex, year, month, type, Integer.parseInt(zhuanMaList1.getList().get(position).getRoomid()), chooiseCompany.getText().toString()));
            }
        });
        hideProgressDialog();
        ptrClass.refreshComplete();//
        zhuanma01Adapter.setOnLoadMoreListener(this, vipUservipUserInfornation);

    }

    @Override
    public void showqueryCurrencyList(final CurrencyListBean currencyListBean) {
        if (currencyListBean != null && currencyListBean.getCurrencys().size() > 0) {
//            roomId = Integer.parseInt(currencyListBean.getCurrencys().get(0).getRoomid());
            //填充廳數據
            //初始化一个空list的adapter，网络错误时使用，第一次加载到数据时重新初始化adapter并绑定recyclevie
            popAdapter = new PopAdapter(R.layout.pop_list_item, currencyListBean);
            clubrecyclerView.setAdapter(popAdapter);
            clubrecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
//           clubrecyclerView.seton
            //集團點擊監聽
            popAdapter.setOnCliCkItemListenerr(new PopAdapter.OnCliCkItemListener() {
                @Override
                public void clickItem(int position) {
                    chooiseCompany.setText(currencyListBean.getCurrencys().get(position).getCurrencyName1());//動態改變集團名稱
                    //查詢最大日期
//                    if (position != 0) {
//                        mPresenter.queryMaxChangemonth(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(), roomId);
//                    } else {
                    isUpdate = true;
                    showProgressDialog("正在查詢");
                    if (month.equals("全年")) {
                        mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), "", year, chooiseCompany.getText().toString());
                    } else {
                        mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                                clientindex, 0, 10, loginBean.getId(), month + "", year + "", chooiseCompany.getText().toString());
                    }
//                    }

                    mClubPopWindow.dissmiss();
                }
            });
            //填充廳數據
            mallRoomListBean = currencyListBean;
//            roomId = allRoomListBean.getRoomList().get(0).getRoomid();//默认第一个厅
//            //查询子户口
            if (queryRegisBean != null && !queryRegisBean.getServerSetting().getServerAddress().equals("")) {
                //查询子户口
                showProgressDialog("请稍等...");
                if (month.equals("全年")) {
                    mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                            clientindex, 0, 10, loginBean.getId(), "", year + "", chooiseCompany.getText().toString());
                } else {
                    mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().getServerProject(), queryRegisBean.getServerSetting().getServerPort(),
                            clientindex, 0, 10, loginBean.getId(), month + "", year + "", chooiseCompany.getText().toString());
                }
            }
        }
    }

//    /**
//     * 初始化头部
//     */
//    private void initHeadView() {
//        if (headView == null) {
//            headView = ResourcesUtils.inflate(R.layout.rv_top_zhuanma01);
//        }
//
//        if (footView == null) {
//            footView = ResourcesUtils.inflate(R.layout.rv_no_more_data);
//        }
//        if (errorView == null) {
//            errorView = ResourcesUtils.inflate(R.layout.view_network_error);
//        }
//        errorView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (month.equals("全年")) {
//                    mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
//                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), "", year);
//                } else {
//                    mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
//                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, loginBean.getId(), month, year);
//                }
//            }
//        });
//
//        tv_jituan_money = headView.findViewById(R.id.tv_jituan_money);
//
//    }

    /**
     * 填充數據
     *
     * @param zhuanMaListbean
     */
    private void initRecycleView(final ZhuanMaList1 zhuanMaListbean) {
        zhuanma01Adapter = new Zhuanma01Adapter(R.layout.item_zhuanma01, zhuanMaListbean.getList());

        vipUservipUserInfornation.setAdapter(zhuanma01Adapter);
    }

    @OnClick({R.id.ibtn_zhuanma_back, R.id.chooise_time, R.id.chooise_company})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ibtn_zhuanma_back:
                pop();
                break;
            case R.id.chooise_time:
                chooisTime();
                break;
            case R.id.chooise_company:
                chooiseCurrency();
                break;
        }
    }

    @Override
    public void initData() {
        super.initData();
        loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
        if (fragment.getArguments() != null) {
            queryRegisBean = (QueryRegisBean) fragment.getArguments().getSerializable(Constants.QUERY_SETTING);
            clientindex = fragment.getArguments().getInt(Constants.CLIENTINDEX, 0);
//            roomname = fragment.getArguments().getString(Constants.ROOMNAME);
            year = fragment.getArguments().getString(Constants.YEAR);
            month = fragment.getArguments().getString(Constants.MONTH);
            roomid = fragment.getArguments().getInt(Constants.ROOMID, 0);
            chooiseTime.setText(year + "/" + month);
            type = fragment.getArguments().getInt(Constants.TYPE, 0);
            currency = fragment.getArguments().getString(Constants.CURRENCYNAMECN);
        }
    }

    /**
     * 时间选择
     */
    private void chooisTime() {
        DialogUIUtils.showDatePick(mActivity, Gravity.CENTER, "选择日期", System.currentTimeMillis() + 60000, DateSelectorWheelView.TYPE_YYYYMM, 0, new DialogUIDateTimeSaveListener() {
            @Override
            public void onSaveSelectedDate(int tag, String selectedDate) {//点击年月监听器
                time1 = selectedDate;
                year = selectedDate.substring(0, 4);
                month = selectedDate.substring(selectedDate.length() - 2, selectedDate.length());
                time2 = time1.replace("-", "/");
                chooiseTime.setText(time2);
                //查询子户口
                isUpdate = true;
                showProgressDialog("加载中...");
                if (month.equals("全年")) {
                    mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), "", year, chooiseCompany.getText().toString());
                    LogUtil.e("canshuzhi========" + clientindex + 0 + 10 + loginBean.getId() + "" + year + currency);
                } else {
                    mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                            getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), month, year, chooiseCompany.getText().toString());
                }
            }

        }).show();
    }

    /**
     * 下拉刷新監聽
     */
    private void reFreshListener() {
        MaterialHeader header = new MaterialHeader(mActivity);
        ptrClass.addPtrUIHandler(header);
        ptrClass.setLastUpdateTimeRelateObject(this);//设置刷新支持时间
        ptrClass.setResistance(1.7f);//设置下拉的阻尼系数，值越大感觉越难下拉
        ptrClass.setDurationToCloseHeader(1000);//设置刷新完成，头部回弹时间，注意和前一个进行区别
        ptrClass.setPullToRefresh(false);//设置下拉过程中执行刷新，我们一般设置为false
        ptrClass.setKeepHeaderWhenRefresh(true);//设置刷新的时候是否保持头部
        ptrClass.setPtrHandler(new PtrDefaultHandler() {               //下拉刷新
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //模拟联网，延迟更新数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (ptrClass != null && mPresenter != null) {
                            isUpdate = true;
                            showProgressDialog("加载中...");
                            LogUtils.e("month123=" + month + "year123=" + year);
                            if (month.equals("全年")) {
                                mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), "", year, chooiseCompany.getText().toString());
                            } else {
                                mPresenter.getZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                                        getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), month, year, chooiseCompany.getText().toString());
                            }
                        } else {
                            hideProgressDialog();
                        }
                    }
                }, 1000);
            }
        });
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        zhuanma01Adapter.loadMoreComplete();
//        //联网加载更多
        if (month.equals("全年")) {
            mPresenter.getMoreZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                    getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), "", year, currency);
        } else {
            mPresenter.getMoreZhuanMa01(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                    getServerProject(), queryRegisBean.getServerSetting().getServerPort(), clientindex, 0, 10, loginBean.getId(), month, year, currency);
        }

    }

    /**
     * 懒加载
     *
     * @param savedInstanceState
     */
    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        if (queryRegisBean != null && loginBean != null) {
            mPresenter.queryCurrencyList(queryRegisBean.getServerSetting().getServerAddress(), queryRegisBean.getServerSetting().
                    getServerProject(), queryRegisBean.getServerSetting().getServerPort());
        }

    }

    private void chooiseCurrency() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0, CENTER);
            // 设置背景颜色变暗
            WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
            lp.alpha = 0.5f;
            mActivity.getWindow().setAttributes(lp);
        } else {
            mClubPopWindow.showAsDropDown(chooiseCompany, 0, 0);
            // 设置背景颜色变暗
            WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
            lp.alpha = 0.5f;
            mActivity.getWindow().setAttributes(lp);
        }
    }

}
